package LuoGu;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;

public class P19022 {
    static class Number {
        int x;
        int y;

        public Number(int x, int y) {
            this.x = x;
            this.y = y;
        }

    }

    static int[][] a;
    static boolean[][] vis;
    static int n;
    static int m;
    static int[] dx = {0, 1, 0, -1, 0};
    static int[] dy = {0, 0, 1, 0, -1};

    public static boolean ifOK(int x, int y, int max) {
        Queue<Number> q = new LinkedList<>();
        q.add(new Number(x, y));
        vis[x][y] = true;
        while (!q.isEmpty()) {
            Number tmp = q.poll();
            int tmpx = tmp.x;
            int tmpy = tmp.y;
            for (int i = 1; i <= 4; i++) {
                int xx = tmpx + dx[i];
                int yy = tmpy + dy[i];
                if (xx < 1 || xx > n || yy < 1 || yy > m || a[xx][yy] > max || vis[xx][yy]) {
                    continue;
                }
                vis[xx][yy] = true;
                if (xx == n) {
                    return true;
                } else {
                    q.add(new Number(xx, yy));
                }
            }
        }
        return false;
    }

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String tmp = br.readLine();
        n = Integer.parseInt(tmp.split(" ")[0]);
        m = Integer.parseInt(tmp.split(" ")[1]);
        a = new int[n + 1][m + 1];
        vis = new boolean[n + 1][m + 1];
        int max = Integer.MIN_VALUE;
        int min = Integer.MAX_VALUE;
        for (int i = 1; i <= n; i++) {
            tmp = br.readLine();
            String[] strs = tmp.split(" ");
            for (int j = 1; j <= m; j++) {
                a[i][j] = Integer.parseInt(strs[j - 1]);
                vis[i][j] = false;
                max = Math.max(max, a[i][j]);
                min = Math.min(min, a[i][j]);
            }
        }
        int left = min;
        int right = max;
        int output = 0;
        while (left <= right) {
            int mid = (left + right) >>> 1;
            for (int i = 1; i <= n; i++) {
                Arrays.fill(vis[i], false);
            }
            if (ifOK(1, 1, mid)) {
                output = mid;
                right = mid - 1;
            } else {
                left = mid + 1;
            }
        }
        System.out.println(output);

    }
}
